package controller;

import implementor.BalancePaymentDaoImplementor;
import implementor.CardDaoImplementor;
import implementor.ChequeDaoImplementor;
import implementor.TransactionCategoryDaoImplementor;
import implementor.TransactionDaoImplementor;
import implementor.TransationPaymentDaoImplementor;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.plaf.basic.BasicBorders.RadioButtonBorder;
import javax.swing.table.DefaultTableModel;

import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

import daoInterface.BalanceDao;
import daoInterface.BalancePaymentDao;
import daoInterface.CardDao;
import daoInterface.ChequeDao;
import daoInterface.TransactionCategoryDao;
import daoInterface.TransactionDao;
import daoInterface.TransationPaymentDao;
import dto.BalancePayment;
import dto.Card;
import dto.Cheque;
import dto.TransactionCategory;
import dto.Transactions;
import dto.TransationPayment;

import utilities.AppUtilites;
import utilities.Constants;
import utilities.ViewUtilites;
import views.accounting.Accounting;

public class AccountingController implements ActionListener{
	private Accounting view;
	private Transactions model;
	private TransactionDao transDao;
	
	private Vector<Transactions> transactios;
    private Vector<Cheque> cheques;
	private Vector<Card> cards;
	private Vector<TransationPayment>transectionPayment;
	private Vector<BalancePayment>balancePayment;
	private static int srNo=1;
	
	
	public AccountingController() {
		
	}

public AccountingController(Accounting view, Transactions model) {
		super();
		this.view = view;
		this.model = model;
		view.addActionListenerOnButtons(this);
		srNo=1;
		AppUtilites.setPaymentMethod(view.getComboBoxPaymentMethod());
		transDao=new TransactionDaoImplementor();
		transactios=new Vector<Transactions>();
		cheques=new Vector<Cheque>();
		cards=new Vector<Card>();
		transectionPayment= new Vector<TransationPayment>();
		balancePayment = new Vector<BalancePayment>();
		
	}

public void setTransectionTypeCategory(String type)
	{
		TransactionCategoryDao cd=new TransactionCategoryDaoImplementor();
		TransactionCategory[] c=null;
		int transectionType = -1;
		if(type.equals("Expense"))
		{
			transectionType=Constants.EXPENSE;
			
		}
		
		if(type.equals("Income"))
		{
			transectionType=Constants.INCOME;
		}
		
		if(type.equals("Expense")||type.equals("Income"))
		{
			
		try {
			c = cd.retrieveArray("type", transectionType+"");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
		String[] items=new String[c.length+1];
		items[0]="--Select Category--";
		for(int i=1;i<=c.length;i++)
		{
			items[i]=c[i-1].getcategoryName();
		}
		ViewUtilites.set_comboBox(view.getCbCategory(), items);
			
	}
	
	public void setAccountingCategoryCombo()
	{
		if(view.getRdbtnExpense().isSelected()==true)
			setTransectionTypeCategory(view.getRdbtnExpense().getActionCommand());

		else if(view.getRdbtnIncome().isSelected()==true)
			setTransectionTypeCategory(view.getRdbtnIncome().getActionCommand());
		
		else if(view.getRdbtnPaySeller().isSelected()==true)
			setTransectionTypeCategory(view.getRdbtnPaySeller().getActionCommand());
		
		else if(view.getRdbtnAcceptPayment().isSelected()==true)
			setTransectionTypeCategory(view.getRdbtnAcceptPayment().getActionCommand());

	}

public void reactToAdd()
{
	String tag=null;
	// creating transection vector
	model=new Transactions();
	
	model.setamt(Double.parseDouble(view.getTfAmount().getText().trim()));
	model.setdate(ViewUtilites.convert(view.getTfDate().getText().trim()));
	String catname=view.getCbCategory().getSelectedItem().toString();
	model.settransCatId(AppUtilites.getTransCatId(catname));
	model.setTransactionCategory();
	model.setcomments(view.getTaDescription().getText());
	String paymentmethodname=view.getComboBoxPaymentMethod().getSelectedItem().toString();
	
	 System.out.println(paymentmethodname+"payment method name");
	 if(paymentmethodname.equals("Cheque"))
	{
		 System.out.println("Added in cheque");
		model.setstatus(Constants.CHEQUE);
		fillInCheque();
		
	}
	else if(paymentmethodname.equals("Card"))
	{
		 System.out.println("Added in card");
		model.setstatus(Constants.CARD);
		fillInCard();
		
	}
	else
		model.setstatus(Constants.CASH);
	    
	transactios.add(model);
	 
	 
	int type=model.getModelTransCat().gettype();
	
	if(type==Constants.EXPENSE)
		tag="Expense";
	else
		tag="Income";
	
	DefaultTableModel dm=(DefaultTableModel) view.getTable().getModel();
	dm.addRow(new Object[]{srNo++,tag,model.getModelTransCat().getcategoryName(),model.getamt(),paymentmethodname,model.getdate()});
	
	
}

/**
 * Saves in cheque vector by creating cheque object
 */
public void fillInCheque()
{
	Cheque cheqdto=new Cheque();
	cheqdto.setamt(Double.parseDouble(view.getTfAmount().getText()));
	cheqdto.setbankName(view.getTfBank().getText().trim());
	cheqdto.setbranchName(view.getTfBranch().getText().trim());
	cheqdto.setdate(view.getTfChequeDate().getText());
	cheqdto.setpaymentMethodId(AppUtilites.getPaymentMethodId(view.getComboBoxPaymentMethod().getSelectedItem().toString()));
	cheqdto.setstatus(Constants.ACTIVE);
	cheques.add(cheqdto);
}

public void fillInCard()
{
	Card carddto=new Card();
	carddto.setPaymentMethodId(AppUtilites.getPaymentMethodId(view.getComboBoxPaymentMethod().getSelectedItem().toString()));
	carddto.setReferenceNo(view.getTfCreditCard().getText());
	//carddto.setCustomerName(view.getTfcustomerName().getText());
	carddto.setCustomerName("Ajay");
	
	cards.add(carddto);
}



private int saveInBalancePayment(BalancePayment balancepayment) throws  Exception
{
	BalancePaymentDao dao = new BalancePaymentDaoImplementor();
	dao.add(balancepayment);
	int autoKey = dao.getAutoGenratedKey();
	return autoKey;
}

private int saveInTransactions(Transactions trans) throws Exception
{
	TransactionDao trandao=new TransactionDaoImplementor();
	trandao.add(trans);
	int autoKey=trandao.getAutoGenratedKey();
	return autoKey;
}

private int saveInTransactionPayment(TransationPayment payment) throws Exception
{
	TransationPaymentDao transpaydao=new TransationPaymentDaoImplementor();
	transpaydao.add(payment);
	
	int autoId=transpaydao.getAutoGenratedKey();
	return autoId;
}

private void saveInCheque(Cheque ch) throws Exception
{
	ChequeDao chdao=new ChequeDaoImplementor();
	chdao.add(ch);
	
}

private void saveInCard(Card ch) throws Exception
{
	CardDao chdao=new CardDaoImplementor();
	chdao.add(ch);
	
}

public void reactToSave() throws SQLException, Exception
{
	try{
		for(int i=0;i<this.transactios.size();i++)
		{
			int j=0;  // to insert in cheque
			int k=0;  // to insert in card
			Transactions temp= this.transactios.get(i);
			BalancePayment balpayment = new BalancePayment();
			balpayment.setamtPaid(temp.getamt());
			balpayment.settotalAmt(temp.getamt());
			balpayment.setbalanceDate(temp.getdate());
			balpayment.settype(temp.getModelTransCat().gettype());
			int balpaymentId= this.saveInBalancePayment(balpayment);
			temp.setbalancePaymentId(balpaymentId);
			int transectionid=this.saveInTransactions(temp);
			System.out.println("Status is "+temp.getstatus());
			if(temp.getstatus()== Constants.CHEQUE)
			{
				TransationPayment tpayment = new TransationPayment();
				tpayment.settransactionId(transectionid);
				int transpaymentId= saveInTransactionPayment(tpayment);
				Cheque ch =cheques.get(j);
				ch.setTransectionPaymentId(transpaymentId);
				saveInCheque(ch);
				j++;
				
			}
			
			if(temp.getstatus()== Constants.CARD)
			{
				TransationPayment tpayment = new TransationPayment();
				tpayment.settransactionId(transectionid);
				int transpaymentId= saveInTransactionPayment(tpayment);
				Card ch =cards.get(k);
				ch.setTransPaymentId(transpaymentId);
				saveInCard(ch);
				System.out.println("SAVED IN CARDS");
				k++;
				
			}
			
			
			
			
		}
		
	}
	catch (Exception e)
	{
		e.printStackTrace();
	}
	

	
}

public boolean validateView()
{
	if(view.getTfAmount().getText().equals("") || view.getTfDate().getText().equals("") 
			|| view.getCbCategory().getSelectedItem().toString().contains("Select") || view.getTaDescription().getText().equals(""))
	{
		return false;
	}
	if(view.getComboBoxPaymentMethod().getSelectedItem().toString().equals("Cheque"))
	{
		if(view.getTfChequeDate().getText().equals("") || view.getTfChequeNo().getText().equals("") 
				|| view.getTfBank().getText().equals("") || view.getTfBranch().getText().equals(""))
		{
			return false;
		}
		
	}
	 else if(view.getComboBoxPaymentMethod().getSelectedItem().toString().equals("Card"))
	{
		if(view.getTfCreditCard().getText().equals(""))
		{
			return false;
		}
	}
	return true;
}

public void refresh()
{
	view.getTfAmount().setText("");
	view.getTfDate().setText("");
	view.getTfChequeNo().setText("");
	view.getTfChequeDate().setText("");
	view.getTfCreditCard().setText("");
	view.getTfcustomerName().setText("");
	view.getTaDescription().setText("");
	view.getComboBoxPaymentMethod().setSelectedIndex(0);
	view.getCbCategory().setSelectedIndex(0);
}
/********************DYNAMIC PART********************************/
	@Override
	public void actionPerformed(ActionEvent e) {
		
		if(e.getSource() instanceof JRadioButton)
		{
			setAccountingCategoryCombo();
		}
		else
		{
			String k=e.getActionCommand();
		if(k.equals("add"))
		{
			if(validateView()==true)
			{
				reactToAdd();
				this.refresh();
				refresh();
			}
			else
			{
				JOptionPane.showMessageDialog(null, "Not added");
			}
		}
		if(k.equals("save"))
		{
			try {
				reactToSave();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		if(k.equals("cheque date"))
		{
			ViewUtilites.makeDateComponent(view.getTfChequeDate());
		}
		if(k.equals("Date"))
		{
			ViewUtilites.makeDateComponent(view.getTfDate());
		}
		
	}
	}

	
}
